﻿using System;

using System.Net;
using System.Web;
using System.Web.Mvc;
using SIG.Model;

using SIG.Service;
using PagedList;

using SIG.Service.Identity;
using SIG.Model.Identity;
using SIG.Infrastructure.Configs;
using SIG.Model.ViewModel.Identity;

namespace SIG.Web.Areas.Admin.Controllers
{
    //[CustomAuthorize(Roles = "Admin")]
    //[Authorize]
    public class UserController : BaseController
    {


        IUserService _userService;
        IRoleService _roleService;
      
        public UserController(IUserService UserService,  IRoleService roleService)
        {
            _userService = UserService;
            _roleService = roleService;
          
        }

        // GET: User
        //  [CustomAuthorize(Roles = "Admin")]
        public ActionResult Index(int? page, DateTime? startDate, DateTime? endDate, string userName)
        {
            var userListVM = new UserListVM
            {
                StartDate = startDate,
                EndDate = endDate,
                Username = userName,           
                PageIndex = (page ?? 1) - 1,
                PageSize = SettingsManager.User.PageSize,
                SetPasswordVM = new SetPasswordVM()
            };

            userListVM.Users = _userService.SearchUsers(userListVM.PageIndex, userListVM.PageSize, userListVM.Username,
                userListVM.StartDate, userListVM.EndDate);
            userListVM.TotalUserCount = _userService.SearchUsersCount(userListVM.Username, userListVM.StartDate, userListVM.EndDate);

            var usersAsIPagedList = new StaticPagedList<User>(userListVM.Users, userListVM.PageIndex + 1, userListVM.PageSize, userListVM.TotalUserCount);
            ViewBag.OnePageOfUsers = usersAsIPagedList;

          

            return View(userListVM);

        }

        // GET: User/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = _userService.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        // GET: User/Create
        public ActionResult Create()
        {
            //var deps = _departmentService.GetAll();
            //var pos = _positionService.GetAll();
            //ViewBag.DepartmentId = new SelectList(deps, "Id", "Title");
            //ViewBag.PositionId = new SelectList(pos, "Id", "Title");
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Create(RegisterVM model)
        {
            if (ModelState.IsValid)
            {
                var result = _userService.Register(model);
                if (result)
                    return Json(true, JsonRequestBehavior.DenyGet);
                else
                    return Json(false, JsonRequestBehavior.DenyGet);

            }
            return Json(false, JsonRequestBehavior.DenyGet);

        }


        public JsonResult IsUserNameUnique(string UserName)
        {
            var user = _userService.GetUserByName(UserName);

            return user == null
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        public JsonResult IsEmailUnique(string Email)
        {
            var user = _userService.GetUserByEmail(Email);

            return user == null
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(Guid? id)
        {

            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var user = _userService.GetById(id);
            if (user == null)
            {
                return HttpNotFound();
            }

            var vm = new ProfileAndRoleVM
            {
                Profiles = new EditProfileVM
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    RealName = user.RealName,
                    Birthday = user.Birthday,                
                    IsActive = user.IsActive,
                    Mobile = user.Mobile,
                    QQ = user.QQ,
                    Email = user.Email,
                    Gender = user.Gender

                },
                Roles = _roleService.GetAll(),
                User = user
            };

            //var deps = _departmentService.GetAll();
            //var pos = _positionService.GetAll();
            //ViewBag.DepartmentId = new SelectList(deps, "Id", "Title", user.DepartmentId);
            //ViewBag.PositionId = new SelectList(pos, "Id", "Title", user.PositionId);


            return View(vm);

        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性，有关 
        // 详细信息，请参阅 http://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Edit([Bind(Include = "UserId,Email,RealName,Birthday,IsActive,DepartmentId,PositionId,Gender,QQ,Mobile")] EditProfileVM profile)
        {
            var user = _userService.GetById(profile.Id);

            if (user == null)
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }

            user.Email = profile.Email;
            user.RealName = profile.RealName;
            user.IsActive = profile.IsActive;
            //user.DepartmentId = profile.DepartmentId;
            //user.PositionId = profile.PositionId;
            user.QQ = profile.QQ;
            user.Mobile = profile.Mobile;
            user.Gender = profile.Gender;
            user.Birthday = profile.Birthday;

            _userService.Update(user);

            return Json(true, JsonRequestBehavior.DenyGet);

        }
        public JsonResult IsEmailUniqueAtEdit(string email, Guid userId)
        {
            var result = _userService.IsEmailUniqueAtEdit(email, userId);

            return result
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult SetRole(Guid? userId, int? roleId, bool isAdd)
        {
            if (userId == null || roleId == null)
            {
                return Json(false, JsonRequestBehavior.DenyGet);
            }
            var user = _userService.GetById(userId);
            var role = _roleService.GetById(roleId);

            if (isAdd)
                user.Roles.Add(role);
            else
                user.Roles.Remove(role);

            _userService.Update(user);

            return Json(true, JsonRequestBehavior.DenyGet);


        }

        // POST: /User/SetPassword
        [HttpPost]

        [ValidateAntiForgeryToken]
        public JsonResult SetPassword(SetPasswordVM model)
        {
            if (ModelState.IsValid)
            {
                var result = _userService.SetPassword(model.UserId, model.NewPassword);
                if (result)
                {
                    return Json(true, JsonRequestBehavior.DenyGet);
                }
            }
            return Json(false, JsonRequestBehavior.DenyGet);
        }


        [HttpPost]
        public JsonResult IsActive(int id)
        {
            var user = _userService.GetById(id);
            if (user != null)
            {
                user.IsActive = !user.IsActive;
                _userService.Update(user);
                return Json(true, JsonRequestBehavior.DenyGet);

            }
            return Json(false, JsonRequestBehavior.DenyGet);
        }


        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        //[ValidateAntiForgeryToken]
        public JsonResult DeleteConfirmed(int id)
        {
            User user = _userService.GetById(id);
  
          
           
            if (user == null)
            {
                AR.Status = Model.Enums.Status.Error;
                AR.Message = "未找到此角色！";
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            if (user.Id.ToString() == SettingsManager.User.Founder)
            {
                AR.Status = Model.Enums.Status.Warning;
                AR.Message = "创始人帐号，不可以删除！";
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            _userService.Delete(user);
            return Json(AR, JsonRequestBehavior.DenyGet);


          
        }


    }
}